package com.siblings.loan.ui.loan.impl

import android.content.Context
import com.siblings.loan.http.IHttpCallback
import com.siblings.loan.status.StatusRepository
import com.siblings.loan.ui.loan.view.ISibLoanCommonView
import com.siblings.loan.utils.helper.ScoreDialogHelper
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.mvp.presenter.MvpPresenter
import org.json.JSONObject

/**
 * Siblings
 * @Author wwdeng
 * @CreateTime: 2024/7/16 13:45
 * @Annotation：审核中、拒绝、放贷中、放贷中法语 Presenter 实现
 */
class SibLoanCommonPresenterImpl(context: Context?) : MvpPresenter<ISibLoanCommonView>(context) {
    private var model: SibLoanCommonModelImpl? = null

    init {
        model = SibLoanCommonModelImpl()
    }

    /**
     * 检查当前状态
     */
    fun checkSibOrderOrApplyStatusAction(data: JSONObject){
        mvpView.showSibLoading()
        loadSibLoanInfoAction()

        //1、判断是否存在 订单状态
        if (data.has("orderStatus")) {
            val orderStatus = data.optString("orderStatus")
            //放款中
            if (StatusRepository(null, orderStatus).isDisbursing()) {
                mvpView.showSibLoanLendingView()
                return
            }
            //申请贷款被拒绝
            if (StatusRepository(null, orderStatus).isRejected()) {
                mvpView.showSibLoanFailedView()
                return
            }
        }

        //2、判断是否存在 贷款申请状态
        if (data.has("applyStatus")){
            val applyStatus = data.optString("applyStatus")
            //审核中
            if (StatusRepository(applyStatus).isReviewing()){
                mvpView.showSibLoanAuditView()
                return
            }
            //被拒绝
            if (StatusRepository(applyStatus).isRejected()){
                mvpView.showSibLoanFailedView()
                return
            }
        }

        //都不存在 ->  显示被拒绝
        mvpView.showSibLoanFailedView()
    }

    /**
     * 获取贷款信息
     */
    private fun loadSibLoanInfoAction(){
        model!!.loadSibLoanInfoAction(object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        mvpView.showSibLoanInfoData(obj!!)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 获取已绑定的账户列表
     */
    fun loadSibLoanAccountAction(){
        model!!.loadSibLoanAccountAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        if (array != null && array.length() > 0) {
                            val accountList = arrayListOf<JSONObject>()
                            for (i in 0..<array.length()){
                                accountList.add(array.optJSONObject(i))
                            }
                            mvpView.showSibLoanAccountList(accountList)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取推荐APP列表
     */
    fun loadSibRecommendAppAction(){
        model!!.loadSibRecommendAppAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        val appList = arrayListOf<JSONObject>()
                        if (obj != null && obj.has("dcProductList")) {
                            val appArray = obj.optJSONArray("dcProductList")
                            if (appArray != null && appArray.length() > 0) {
                                for (i in 0..<appArray.length()) {
                                    appList.add(appArray.optJSONObject(i))
                                }
                            }
                        }
                        mvpView.setSibRecommendAppList(appList)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView.showSibToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 只有审核中或放款中需要调此接口
     * 获取评分配置
     */
    fun loadSibScoreCommentAction() {
        model!!.loadSibScoreCommentAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    ScoreDialogHelper.showStarDialog(mvpView.getContext()!!,obj,true)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitSibBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        model!!.submitSibBindAccountAction(mobile,walletChannel,bindFlag,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadSibLoanAccountAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val spData = SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON)
                                val commonData = JSONObject(spData)
                                val customize = commonData.optJSONObject("customize")
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView.showSibBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView.showSibToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteSibAccountAction(ids: String) {
        mvpView.showSibLoading()
        model!!.deleteSibAccountAction(ids,object: IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView.showSibToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        //刷新列表
                        loadSibLoanAccountAction()
                    }
                    else -> {
                        val msg = data.optString("msg")
//                        mvpView!!.showCedToast(msg)
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
                mvpView.showSibToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView.hideSibLoading()
            }
        })
    }
}